package com.lifeng.config.datasource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Map;

/**
 * 动态数据源
 */
public class DynamicDataSource extends AbstractRoutingDataSource{
    protected static final Logger logger = LoggerFactory.getLogger(DynamicDataSource.class);
    public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources){
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey()    {
        return DynamicDataSourceContextHolder.getDateSoureType();
    }

    /**
     * 重写此方法是为了看到底使用哪个数据源详细信息
     * 不写也没事
     * */
    @Override
    protected DataSource determineTargetDataSource() {
        DataSource dataSource = super.determineTargetDataSource();
        try {
            logger.debug("当前使用的数据源信息:catalog:"+ dataSource.getConnection().getCatalog()+",MetaData:"+
                    dataSource.getConnection().getMetaData());
        }catch (Exception e){
            logger.error("获取数据源对应的connection信息异常");
        }
        return dataSource;
    }
}